from rest_framework.views import APIView
from rest_framework.response import Response
from blog.models import User
from blog.utils.jwt_auth import create_token, get_user_id
from django.contrib.auth.hashers import make_password, check_password
from django.core.paginator import Paginator


class LoginView(APIView):
    authentication_classes = []

    def post(self, request, *args, **kwargs):
        try:
            username = request.data.get('username')
            password = request.data.get('password')
            user = User.objects.filter(status=1, username=username).first()

            if not user:
                return Response({'status': 404, 'msg': '账号或密码不正确'})
            if check_password(password, user.password):
                token = create_token({'id': user.id, 'username': username})
                data = {'id': user.id, 'name': user.name, 'Authorization': token, 'photo': user.photo}
                return Response({'status': 200, 'msg': '登陆成功', 'data': data})
            else:
                return Response({'status': 404, 'msg': '账号或密码不正确'})
        except Exception as e:
            # print(e.args)
            return Response({'status': 204, 'msg': '遇到了异常错误', 'error': e.args})


class AddUserView(APIView):
    authentication_classes = []

    def post(self, request, *args, **kwargs):
        try:
            username = request.data.get('username')
            password = request.data.get('password')
            name = request.data.get('name')
            tel = request.data.get('tel')
            sex = request.data.get('sex')
            email = request.data.get('email')
            is_admin = request.data.get('is_admin')
            user = User.objects.filter(status=1, username=username).first()
            if not user:
                user = User()
                user.username = username
                user.password = make_password(password)
                if name is None:
                    user.name = "user"
                else:
                    user.name = name
                if tel:
                    user.tel = tel

                if sex is None:
                    sex = 1
                user.sex = sex
                if email:
                    user.email = email
                user.photo = "/static/images/headProtraitSmall.png"
                if is_admin:
                    user.is_admin = is_admin
                else:
                    user.is_admin = 0
                user.save()

                return Response({'status': 200, 'msg': '创建成功'})
            else:
                return Response({'status': 404, 'msg': '用户名重复'})

        except Exception as e:
            return Response({'status': 204, 'msg': '遇到了异常错误', 'err': e.args})


class ListMemberView(APIView):
    def get(self, request, *args, **kwargs):
        try:
            page = request.GET.get('page')
            limit = request.GET.get('limit')
            name = request.GET.get('username')
            user = []
            if name is None:
                user = User.objects.filter(status=1)
            else:
                user = User.objects.filter(status=1, name__contains=name)
            if len(user) == 0:
                return Response({'status': 200, 'msg': "获取成功", 'count': 0, 'data': user})
            ptr = Paginator(user, limit)
            user_list = []
            for user in ptr.page(page):
                res = {'id': user.id, 'name': user.name, 'photo': user.photo, 'date': user.create_time,
                       "email": user.email, 'tel': user.tel}
                if user.sex == 0:
                    res['sex'] = "男"
                else:
                    res['sex'] = "女"

                user_list.append(res)
            return Response({'status': 200, 'msg': "获取成功", 'count': ptr.count, 'data': user_list})
        except Exception as e:
            # print(e.args)
            return Response({'status': 204, 'msg': '遇到了异常错误', 'err': e.args})


class GetOneMemberView(APIView):
    def get(self, request, *args, **kwargs):
        try:
            query = User.objects.filter(status=1, id=request.GET.get('id')).first()
            user = {'id': query.id, 'username': query.username, 'name': query.name,
                    'date': query.create_time, "tel": query.tel,
                    "email": query.email, "sex": query.sex}
            data = {'status': 200, 'msg': "获取成功", 'data': user}
            return Response(data)
        except Exception as e:
            # print(e.args)
            return Response({'status': 204, 'msg': '遇到了异常错误', 'err': e.args})


class ChangePasswordView(APIView):
    def post(self, request, *args, **kwargs):
        try:
            id = request.data.get('id')
            old_password = request.data.get('old_password')
            new_password = request.data.get('new_password')
            user = User.objects.filter(status=1, id=id).first()

            if not user:
                return Response({'status': 204, 'msg': '用户不存在'})

            if check_password(old_password, user.password):
                user.password = make_password(new_password)
                user.save()
                return Response({'status': 200, 'msg': '修改成功'})
            else:
                return Response({'status': 204, 'msg': '原密码不正确'})
        except Exception as e:
            # print(e.args)
            return Response({'status': 204, 'msg': '遇到了异常错误', 'err': e.args})


class UpdateUserView(APIView):
    def post(self, request, *args, **kwargs):
        try:
            id = request.data.get('id')
            name = request.data.get('name')
            sex = request.data.get('sex')
            tel = request.data.get('tel')
            email = request.data.get('email')
            user = User.objects.filter(status=1, id=id).first()
            if not user:
                return Response({'status': 204, 'msg': '用户不存在'})
            if name:
                user.name = name
            if sex:
                user.sex = sex
            if tel:
                user.tel = tel
            if email:
                user.email = email
            user.save()
            return Response({'status': 200, 'msg': '修改成功'})

        except Exception as e:
            return Response({'status': 204, 'msg': '遇到了异常错误', 'err': e.args})


class delUserView(APIView):
    def post(self, request, *args, **kwargs):
        try:
            id = request.data.get('id')
            user = User.objects.filter(status=1, id=id).first()
            user.status = 0
            user.save()
            return Response({'status': 200, 'msg': '删除成功'})
        except Exception as e:
            return Response({'status': 204, 'msg': '遇到了异常错误', 'err': e.args})


class UpdateInfo(APIView):
    def post(self, request, *args, **kwargs):
        try:
            token = request.META.get('HTTP_AUTHORIZATION')
            user_id = get_user_id(token)
            name = request.data.get('id')
            sex = request.data.get('sex')
            tel = request.data.get('tel')
            email = request.data.get('email')
            photo = request.data.get('photo')
            user = User.objects.filter(status=1, id=user_id).first()
            if name:
                user.name = name
            if sex:
                user.sex = sex
            if tel:
                user.tel = tel
            if email:
                user.email = email
            if photo:
                user.photo = photo
            user.save()
            return Response({
                'status': 200,
                'msg': '修改成功'
            })
        except Exception as e:
            return Response({'status': 204, 'msg': '遇到了异常错误', 'err': e.args})
